<?php 
$orderIds = $this->getRequest()->getPost('order_ids');
$_coreHelper = $this->helper('core');
$startDate = $this->getRequest()->getParam('start_date','');
$endDate = $this->getRequest()->getParam('end_date','');
$province_id = $this->getRequest()->getParam('province_id')?$this->getRequest()->getParam('province_id'):533;
$city_id = $this->getRequest()->getParam('city_id')?$this->getRequest()->getParam('city_id'):160;
$website_id = $this->getRequest()->getParam('website_id');

$session = Mage::getSingleton('admin/session');
$roleId = $session->getUser()->getRoleId();
$roles = Mage::helper('zgb')->getUserRoles();
$zgb = Mage::helper('zgb');
$ids = array(0);
$storeIds = array(0);

$resource = Mage::getSingleton('core/resource');
$db = $resource->getConnection('core_read');

$items = array();

if($zgb->getRoleId('manufacturer') == $roleId)
{
	$manufacturer = Mage::getModel('zgb/manufacturer')->loadByAdminId($session->getUser()->getId());
	$products = Mage::getModel('catalog/product')->getCollection()->addAttributeToFilter('manufacturer_id', array('eq'=>$manufacturer->getId()));
	foreach($products as $product)
	{
		if(!in_array($product->getId(),$ids))
		{
			$ids[] = $product->getId();
		}
	}

	$sql = "select product_id,name,o.store_id,sum(qty_ordered) as qty from sales_flat_order_item as item left join sales_flat_order as o on item.order_id=o.entity_id where 1=1";


	if($ids && $roleId != 1)
	{
		$sql .= " and product_id in (".implode(',',$ids).")";
	}

}else if($zgb->getRoleId('dealer') == $roleId){
	$dealer = Mage::getModel('zgb/dealer')->loadByAdminId($session->getUser()->getId());

	$warehouses = $dealer->getWarehouseIds();
	$orders = Mage::getModel('sales/order')->getCollection()->addFieldToFilter('warehouse_id', array('in'=>$warehouses));

	$orderIds = array(0);
	foreach($orders as $order)
	{
		$orderIds[] = $order->getId();
	}

	$sql = "select product_id,name,o.store_id,sum(qty_ordered) as qty from sales_flat_order_item as item left join sales_flat_order as o on item.order_id=o.entity_id where 1=1";
	$sql .= " and o.entity_id in (".implode(',', $orderIds).")";
}
else
{
	$sql = "select product_id,name,o.store_id,sum(qty_ordered) as qty from sales_flat_order_item as item left join sales_flat_order as o on item.order_id=o.entity_id where 1=1";
}

if($startDate)
{
	$sql .= " and o.created_at>= '{$startDate} 00:00:00'";
}

if($endDate)
{
	$sql .= " and o.created_at<= '{$endDate} 23:59:59'";
}

if($website_id)
{
	$website = Mage::getModel('core/website')->load($website_id);
	if($website && $website->getId())
	{
		$store = $website->getStoreCollection()->getFirstItem();
		if($store && $store->getId())
		{
			$sql .= " and o.store_id='{$store->getId()}'";
		}
	}
}

if(!$website_id && $city_id)
{
	$websites = Mage::getModel('core/website')->getCollection()->addFieldToFilter('city_id', array('eq'=>intval($city_id)));
	$storeIds = array();
	foreach($websites as $website)
	{
		$store = $website->getStoreCollection()->getFirstItem();
		if($store && $store->getId())
		{
			$storeIds[] = $store->getId();
		}
	}
	if(empty($storeIds)) $storeIds[] = 0;
	$sql .= " and o.store_id in (".implode(',', $storeIds).")";
}

$sql .= " group by product_id,o.store_id";
//echo $sql;
$query = $db->query($sql);
$items = $query->fetchAll();


// if($zgb->getRoleId('dealer') == $roleId)
// {
	
// 	if($website_id)
// 	{
// 		$website = Mage::getModel('core/website')->load($website_id);
// 		if($website && $website->getId())
// 		{
// 			$store = $website->getStoreCollection()->getFirstItem();
// 			if($store && $store->getId())
// 			{
// 				if(in_array($store->getId(),$storeIds))
// 				{
// 					$sql .= " and o.store_id='{$store->getId()}'";
// 				}
// 				else
// 				{
// 					$sql .= " and o.store_id='0'";
// 				}
// 			}
// 		}
// 	}
// 	else
// 	{
// 		if($city_id)
// 		{
// 			$websites = Mage::getModel('core/website')->getCollection()->addFieldToFilter('city_id', array('eq'=>intval($city_id)));
// 			$cityStoreIds = array();
// 			foreach($websites as $website)
// 			{
// 				$store = $website->getStoreCollection()->getFirstItem();
// 				if($store && $store->getId())
// 				{
// 					$cityStoreIds[] = $store->getId();
// 				}
// 			}
// 			foreach($cityStoreIds as $key=>$csid)
// 			{
// 				if(!in_array($csid, $storeIds)) unset($cityStoreIds[$key]); 
// 			}
// 			if(empty($cityStoreIds)) $cityStoreIds[] = 0;
// 			$sql .= " and o.store_id in (".implode(',', $cityStoreIds).")";
// 		}
// 		else
// 		{
// 			$sql .= " and o.store_id in (".implode(',',$storeIds).")";
// 		}
		
// 	}
// }
// else
// {
	
// }


if($items)
{
	$temps = array();
	foreach($items as $item)
	{
		$store = Mage::getModel('core/store')->load($item['store_id']);
		$product = Mage::getModel('catalog/product')->load($item['product_id']);
		$cids = $product->getCategoryIds();
		if($cids){
			$category = Mage::getModel('catalog/category')->load($cids[0]);
		}
		$temps[] = array('name'=>$item['name'],
			'main_category'=>'全部分类',
			'sub_category'=>$category->getName(),
			'store_id'=>$item['store_id'],
			'website_name'=>$store->getName(),
			'unit'=>$product->getAttributeText('unit'),
			'qty'=>$item['qty']);
		
	}
	$items = $temps;
}

if($zgb->getRoleId('manufacturer')==$roleId && !$ids) $items = array();

?>

<div class="print">
	<div class="report-header">
		<h2>商品销售统计报表（按区域）</h2>
		<div class="search-box">
			<form name="report_form" id="report_form" action="" method="get">
				时间周期：<input type="text" name="start_date" id="start_date" value="<?php echo $startDate;?>" class="laydate-icon"/> 至 <input type="text" name="end_date" id="end_date" value="<?php echo $endDate;?>" class="laydate-icon"/></br>
				区域：
					<?php
                        $provinces = array();
                        $collection = Mage::getModel('directory/region')->getCollection()->addFieldToFilter('country_id', array('eq'=>'CN'));
                        $provinces[] = array('value'=>'','label'=>'-请选择-');
                        foreach($collection as $region)
                        {
                            $provinces[] = array('value'=>$region->getId(),'label'=>$region->getName());
                        }
                    ?>
					<select id="r_province_id" name="province_id">
						<?php foreach($provinces as $prov):?>
							<option value="<?php echo $prov['value'];?>" <?php if($prov['value']==$province_id) echo 'selected';?>><?php echo $prov['label'];?></option>
						<?php endforeach;?>
					</select>
					<?php
					$citys = array();
		            $citys[] = array('value'=>'','label'=>'-请选择-');
		            if($province_id)
		            {
			            $collection = Mage::getModel('chinaarea/city')->getCollection()->addFieldToFilter('region_id',array('eq'=>$province_id));
				        foreach($collection as $city)
				        {
				            $citys[] = array('value'=>$city->getId(), 'label'=>$city->getDefaultName());
				        }
			    	}
					?>
					<select id="r_city_id" name="city_id">
						<?php foreach($citys as $city):?>
							<option value="<?php echo $city['value'];?>" <?php if($city['value']==$city_id) echo 'selected';?>><?php echo $city['label'];?></option>
						<?php endforeach;?>
					</select>
					<?php
					$areas[] = array('value'=>'','label'=>'-请选择-');
					if($city_id){
				        $resource = Mage::getSingleton('core/resource');
				        $db = $resource->getConnection('core_read');
				        $sql = "select `area`.*,website.website_id from directory_country_area `area` right join core_website website on `area`.area_id=website.area_id where `area`.city_id='{$city_id}'";
				        $query = $db->query($sql);
				        $collection = $query->fetchAll();
				        
				        foreach($collection as $area)
				        {
				            $areas[] = array('value'=>$area['website_id'], 'label'=>$area['default_name']);
				        }
			    	}
					?>

					<select id="r_website_id" name="website_id">
						<?php foreach($areas as $area):?>
							<option value="<?php echo $area['value'];?>" <?php if($area['value']==$website_id) echo 'selected';?>><?php echo $area['label'];?></option>
						<?php endforeach;?>
					</select>
					<input type="button" value="统计" id="apply"/>
			</form>
		</div>
	</div>
	<script type="text/javascript">
		laydate({
		    elem: '#start_date',
		    format: 'YYYY-MM-DD',
		    event: 'focus'
		});
		laydate({
		    elem: '#end_date',
		    format: 'YYYY-MM-DD',
		    event: 'focus'
		});
	</script>
	<div class="order-print">
		<table class="data-table">
			<tr>
				<td>商品名称</td>
				<!-- <td width="8%">省份</td>
				<td width="8%">市</td> -->
				<td width="8%">区县</td>
				<td width="8%">单位</td>
				<td width="8%">数量</td>
			</tr>
			<?php foreach($items as $item):?>
			<tr>
				<td><?php echo $item['name']; ?></td>
				<!-- <td><?php ?></td>
				<td><?php ?></td> -->
				<td><?php echo $item['website_name'] ?></td>
				<td><?php echo $item['unit'] ?></td>
				<td><?php echo intval($item['qty']); ?></td>
			</tr>
			<?php endforeach;?>
		</table>
	</div>
</div>
<script type="text/javascript">
(function($){
	$("#apply").click(function(){
		if($("#r_province_id").val())
		{
			if(!$("#r_city_id").val())
			{
				alert("请选择城市");
				return;
			}
		}
		$("#report_form").submit();
	});
	// if($('#r_province_id').val()=='') 
 //    {
 //        $('#r_city_id').attr('disabled',true);
 //        $('#r_website_id').attr('disabled',true);
 //    }
	$('#r_province_id').change(function(){      
        $.getJSON('<?php echo $this->getUrl('zgb/ajax/citys')?>?id='+$(this).val(), function(data){
            $('#r_city_id').empty();
            $('#r_website_id').empty();
            var option = $('<option>').val('').text('-请选择-');
            $('#r_website_id').append(option);
            for(var i=0; i<data.length;i++)
            {
                var option = $('<option>').val(data[i].value).text(data[i].label);
                $('#r_city_id').append(option);
            }
            $('#r_city_id').attr('disabled',false);
            $('#r_website_id').attr('disabled',true);
            $('#r_city_id').find('option:first').attr('selected',true);
        });
    });

    $("#r_city_id").change(function(){
        $('#r_website_id').attr('disabled',true);
        $.getJSON('<?php echo $this->getUrl('zgb/ajax/websites')?>?id='+$(this).val(), function(data){
            $('#r_website_id').empty();
            for(var i=0; i<data.length;i++)
            {
                var option = $('<option>').val(data[i].value).text(data[i].label);
                $('#r_website_id').append(option);
            }
            $('#r_website_id').attr('disabled',false);
            $('#r_website_id').find('option:first').attr('selected',true);
        });
    });


})(jQuery);
</script>